import re
import time
import requests
from lxml import etree
import random
import requests
from fake_useragent import UserAgent

class WJX():
    def __init__(self):
        # 填空题的备选答案
        self.fillblank_answer = {
            "answer1": ["吃饭", "睡觉", "打豆豆", "其实我就是豆豆", "豆豆霸王"]
        }

        # 发送请求的请求头
        self.headers = {
	        "Accept": "*/*",
	        "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
	        "Cache-Control": "no-cache",
	        "Connection": "keep-alive",
	        "Host": "www.wjx.cn",
	        "Pragma": "no-cache",
	        "Sec-Fetch-Dest": "document",
	        "Sec-Fetch-Mode": "navigate",
	        "Sec-Fetch-Site": "none",
	        "Sec-Fetch-User": "?1",
	        "Upgrade-Insecure-Requests": "1",
	        "User-Agent": str(UserAgent().random),
        }

    def _jqsign(self, jqnonce, ktimes):
        '''
            基于JavaScript改写的加密算法
        '''
        b = ktimes % 10
        b = 1 if b == 0 else b
        return "".join([chr(ord(j)^b) for j in jqnonce])

    def fetch_query(self, code):
        '''
            从问卷星网站上拿到所有的题目，后续提交答案的时候就不再读取问卷了‘
            :param code: 问卷的id
        '''
        self.query_code = code
        query_url = f"https://www.wjx.cn/jq/{code}.aspx"

        self.s = requests.Session()
        resp = self.s.get(url=query_url, headers=self.headers).text

        self.rn = re.search('var rndnum="(.*?)";', resp, re.S).group(1)
        self.jqnonce = re.search('var jqnonce="(.*?)";', resp, re.S).group(1)
        self.starttime = re.search('var starttime="(.*?)";', resp, re.S).group(1)
        
        html = etree.HTML(resp)
        questions = html.xpath('//div[@class="div_table_radio_question"]')
        question_lst = []
        for q in questions:
            if q.xpath(".//textarea"): # 填空题
                question_lst.append({
                    "type": "fillblank",
                    "answer": "answer1"
                    })
            elif q.xpath(".//input[@type='radio']"): # 单选题
                opts_count = len(q.xpath(".//input[@type='radio']"))
                question_lst.append({
                    "type": "single",
                    "opts_count": opts_count
                    })
            elif q.xpath(".//input[@type='checkbox']"): # 多选题
                opts_count = len(q.xpath(".//input[@type='checkbox']"))
                question_lst.append({
                    "type": "multiple",
                    "opts_count": opts_count
                    })
        self.q_lst = question_lst

        # 拿到问卷以后稍微歇一歇，让服务器缓一缓，减少输入验证码的概率
        time.sleep(1)


    def post(self):
        submitdata = ""
        for index,item in enumerate(self.q_lst):
            if submitdata:
                submitdata += "}"

            if item['type'] == "fillblank":
                tmp = random.choice(self.fillblank_answer[item['answer']])
            elif item['type'] == "single":
                tmp = random.randint(1, item['opts_count'])
            elif item['type'] == "multiple":
                opts_count = item['opts_count']
                tmp = "|".join([str(i) for i in random.sample(range(1, opts_count+1), random.randint(1, opts_count))])

            submitdata += f"{index+1}${tmp}"

        post_url = "https://www.wjx.cn/joinnew/processjq.ashx"
        headers = self.headers.copy()
        headers.update({
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Origin': 'https://www.wjx.cn',
            'Pragma': 'no-cache',
            'Referer': f'https://www.wjx.cn/jq/{self.query_code}.aspx',
            'X-Requested-With': 'XMLHttpRequest',
            })

        ktimes = random.randint(91, 173)

        params = {
            "curid": self.query_code,
            "starttime": self.starttime,
            "source": "directphone",
            "submittype": 1,
            "ktimes": ktimes,
            "hlv": 1,
            "rn": self.rn,
            "jpm": 2,
            "t": int(time.time() * 1000),
            "jqnonce": self.jqnonce,
            "jqsign": self._jqsign(self.jqnonce, ktimes)
        }

        form_data = {
            "submitdata": submitdata        
        }

        print(self.s.post(url=post_url, headers=headers, data=form_data, params=params).text)

if __name__ == "__main__":
    wjx = WJX()
    while True:
        wjx.fetch_query("68314376")
        wjx.post()
        time.sleep(random.randint(8, 10)) # 脚本无处理验证码的能力，所以要控制好提交问卷的频率